package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.entity.BackResponseEntity;
import com.example.demo.entity.BookComment;
import com.example.demo.entity.BooksInformation;
import com.example.demo.entity.requestJson.*;
import com.example.demo.entity.responseJson.ListResult;
import com.example.demo.entity.responseJson.OnelevelCommentRes;
import com.example.demo.entity.responseJson.TwoLevelCommentRes;
import com.example.demo.enums.ErrCodeEnum;
import com.example.demo.mapper.BookCommentMapper;
import com.example.demo.mapper.BooksInformationMapper;
import com.example.demo.service.BookCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 文章评论表(BookComment)Service层
 *
 * @author 杨丽辉
 * @since 2021-03-11 14:08:48
 */
@Service
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
public class BookCommentServiceImpl implements BookCommentService {
        @Autowired
        private BookCommentMapper bookCommentMapper;
        @Autowired
        private BooksInformationMapper booksInformationMapper;


 /**
     * 通过ID和其他条件查询单条数据
     *
     * @param bookComment 实例对象
     * @return 实例对象
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
     public BookComment queryBookCommentLimit1(BookComment bookComment){
     return  bookCommentMapper.queryBookCommentLimit1( bookComment);
     }
     
 /**
     * 查询指定行数据
     * @param bookComment 实例对象
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public   List<BookComment> queryAllBookCommentByLimit( BookComment bookComment, Integer offset,  Integer limit){
   return bookCommentMapper.queryAllBookCommentByLimit(bookComment, offset,limit);
  }

  /**
     * 查询数据条数
     * @return 条数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public int countAllBookComment(BookComment bookComment){
   return bookCommentMapper.countAllBookComment( bookComment);
   }
   /**
     * 通过实体作为筛选条件查询
     *
     * @param bookComment 实例对象
     * @return 对象列表
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public List<BookComment> queryAllBookComment(BookComment bookComment){
   return bookCommentMapper.queryAllBookComment(bookComment);
   }
  /**
     * 新增数据
     *
     * @param bookComment 实例对象
     * @return 影响行数
     */
     @Override
   @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public int insertBookComment(BookComment bookComment){
    return  bookCommentMapper.insertBookComment( bookComment);
    }
  /**
     * 修改数据
     *
     * @param bookComment 实例对象
     * @return 影响行数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
     public  int updateBookComment(BookComment bookComment){
         return bookCommentMapper.updateBookComment( bookComment);
     }

    /**
     * 通过主键删除数据
     * @param id 主键
     * @return 影响行数
     */
      @Override
  @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public  int deleteBookCommentById(String id){
   return  bookCommentMapper.deleteBookCommentById( id);
   }
     /**
     * 通过主键列表删除，列表长度不能为0
     * @param list 集合
     * @return 条数
     */
      @Override
  @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public  int deleteBookCommentByIds( List<String> list){
    return  bookCommentMapper.deleteBookCommentByIds(  list);
  }
    
       /**
     * 通过主键修改实体列表，列表长度不能为0，注意：当实体属性为null时，对应的列也会别更新为null
     * @param list 集合
     * @return 条数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public int updateBookCommentBatch( List<BookComment> list){
   return  bookCommentMapper.updateBookCommentBatch(list);
   }
    /**
     * 批量其他列,除主键以外的列，列表长度不能为0,字段是空的就置为null
     * @param list 集合
     * @return 条数
     */
      @Override
  @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
 public   int insertBookCommentBatch( List<BookComment> list){
 return bookCommentMapper.insertBookCommentBatch( list);
 }
      /**
     * 通过实体非空属性删除
     * @param bookComment  实体
     * @return 条数
     */
        @Override
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public   int deleteBookCommentByEntity( BookComment bookComment){
  return  bookCommentMapper.deleteBookCommentByEntity(  bookComment);
  }
    /**
     * 通过实体不为空的属性作为筛选条件查询列表
     * @param bookComment  实体
     * @return list
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public  List<BookComment> listBookCommentByEntity(BookComment bookComment){
   return bookCommentMapper.listBookCommentByEntity( bookComment);
   }

 /**
     * 新增实体属性不为null的列
     * @param bookComment  实体
     * @return 条数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public  int insertBookCommentSelect( BookComment bookComment){
      return bookCommentMapper.insertBookCommentSelect( bookComment);

   }
   
      /**
     * 批量新增新增实体属性不为null的列
     * @param list  实体
     * @return 条数
     */
        @Override
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public  int insertBookCommentListSelect( List<BookComment> list){

     return bookCommentMapper.insertBookCommentListSelect( list);
      }
     /**
     * 通过实体不为空的属性作为筛选条件查询单个
     * @param bookComment  实体
     * @return 单个
     */
     @Override
   @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public  BookComment getBookCommentByEntity(BookComment bookComment){
     return  bookCommentMapper.getBookCommentByEntity(bookComment);
    }

/**
 * 发布一级评论
 * level直接置为1
 * 1.在章节内评论需要传章节id和章节名称
 * 2.在书籍详情页直接评论不需要传章节id和章节名称
 * */
    @Override
    public BackResponseEntity<Object> putOneLevelComment(PutOneLevelCommentReq putOneLevelCommentReq){
        String userId = null;
        String bookId = null;
        String content = null;
        String chapterId = null;

        if(!ObjectUtils.isEmpty(putOneLevelCommentReq.getUserId())){
            userId = putOneLevelCommentReq.getUserId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(putOneLevelCommentReq.getBookId())){
            bookId = putOneLevelCommentReq.getBookId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(putOneLevelCommentReq.getContent())){
            content = putOneLevelCommentReq.getContent()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(putOneLevelCommentReq.getChapterId())){
            chapterId = putOneLevelCommentReq.getChapterId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(bookId)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_0, "参数缺失");
        }

        BookComment bookComment = new BookComment();
        bookComment.setUserId(userId);
        bookComment.setBookId(bookId);
        bookComment.setContent(content);
        bookComment.setChapterId(chapterId);
        bookComment.setCommentLevel(1);
        bookComment.setCreateTime(LocalDateTime.now());

        int i = bookCommentMapper.insert(bookComment);

        if(i > 0){
            BooksInformation booksInformation = new BooksInformation();
            int count = booksInformationMapper.countCommentCount(bookId) +1;
            booksInformation.setBooksId(bookId);
            booksInformation.setCommentCount(count);

            booksInformationMapper.updateBooksInformation(booksInformation);

            return BackResponseEntity.success(ErrCodeEnum.unknown_1022, "发表一级评论成功");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1023, "发表一级评论失败");
        }
    }

    /**
     * 查看一级评论
     * 1.在书籍详情页查看整本书评论：传book_id
     * 2.在书中查看某一章节评论：传chapter_id,或者传book_id和chapter_id
     * */
    @Override
    public BackResponseEntity<ListResult<List<OnelevelCommentRes>>> queryOneComment(QueryBookCommentReq bookCommentReq){
        String bookId = null;
        String chapterId = null;

        if(!ObjectUtils.isEmpty(bookCommentReq.getBookId())){
            bookId = bookCommentReq.getBookId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(bookCommentReq.getChapterId())){
            chapterId = bookCommentReq.getChapterId()
                    .trim();
        }

       if(ObjectUtils.isEmpty(chapterId)){
           int count = bookCommentMapper.countbookComment(Wrappers.<BookComment>query().eq("book_id",bookId)
                   .eq("comment_level",1));
           List<OnelevelCommentRes> list = bookCommentMapper.querybonelevelComment(Wrappers.<BookComment>query().eq("c.book_id",bookId)
                   .eq("comment_level",1)
                   .orderByDesc("c.create_time"));
           ListResult<List<OnelevelCommentRes>> listResult = new ListResult(count,list);

           return BackResponseEntity.success(ErrCodeEnum.unknown_0, listResult , "");
       }else {
           int count = bookCommentMapper.countchapterComment(Wrappers.<BookComment>query().eq("chapter_id",chapterId));

           List<OnelevelCommentRes> list = bookCommentMapper.querybonelevelComment(Wrappers.<BookComment>query().eq("c.chapter_id",chapterId)
                   .eq("comment_level",1)
                   .orderByDesc("c.create_time"));
           ListResult<List<OnelevelCommentRes>> listResult = new ListResult(count,list);

           return BackResponseEntity.success(ErrCodeEnum.unknown_0, listResult , "");
       }
    }

    /**
     * 回复一级评论（二级评论）
     * */
    @Override
    public BackResponseEntity<Object> putTwoLevelComment(PutBookTwoCommentReq putBookTwoCommentReq){
        String userId = null;
        String bookId = null;
        String parentCommentId = null;
        String parentCommentUserId = null;
        String content = null;

        if(!ObjectUtils.isEmpty(putBookTwoCommentReq.getUserId())){
            userId = putBookTwoCommentReq.getUserId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(putBookTwoCommentReq.getBookId())){
            bookId = putBookTwoCommentReq.getBookId()
                    .trim();
        }

        if(!ObjectUtils.isEmpty(putBookTwoCommentReq.getParentCommentId())){
            parentCommentId = putBookTwoCommentReq.getParentCommentId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(putBookTwoCommentReq.getParentCommentUserId())){
            parentCommentUserId = putBookTwoCommentReq.getParentCommentUserId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(putBookTwoCommentReq.getContent())){
            content = putBookTwoCommentReq.getContent()
                    .trim();
        }
       if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(bookId) ||
          ObjectUtils.isEmpty(parentCommentId) || ObjectUtils.isEmpty(parentCommentUserId) || ObjectUtils.isEmpty(content)){
           return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
       }

       BookComment bookComment = new BookComment();
       bookComment.setUserId(userId);
       bookComment.setBookId(bookId);
       bookComment.setParentCommentId(parentCommentId);
       bookComment.setParentCommentUserId(parentCommentUserId);
       bookComment.setContent(content);
       bookComment.setCommentLevel(2);
       bookComment.setCreateTime(LocalDateTime.now());

       int i = bookCommentMapper.insert(bookComment);

       if(i > 0){
           BooksInformation booksInformation = new BooksInformation();
           int count = booksInformationMapper.countCommentCount(bookId)+1;
           booksInformation.setBooksId(bookId);
           booksInformation.setCommentCount(count);

           booksInformationMapper.updateBooksInformation(booksInformation);

           return BackResponseEntity.success(ErrCodeEnum.unknown_0, "回复一级评论成功");
       }else {
           return BackResponseEntity.success(ErrCodeEnum.unknown_1025, "回复一级评论失败");
       }
    }

    /**
     * 查看二级评论
     * 1.传父评论id：传parentCommentId
     * */
    @Override
    public BackResponseEntity<ListResult<List<TwoLevelCommentRes>>> queryTwoeComment(DeleteReq deleteReq){
        String parentCommentId = null;

        if(!ObjectUtils.isEmpty(deleteReq.getId())){
            parentCommentId = deleteReq.getId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(parentCommentId)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }
        int count = bookCommentMapper.countbooktwoComment(Wrappers.<BookComment>query().eq("parent_comment_id",parentCommentId)
                .eq("comment_level",2));

        List<TwoLevelCommentRes> list = bookCommentMapper.querybtwoelevelComment(Wrappers.<BookComment>query().eq("parent_comment_id",parentCommentId)
                .eq("comment_level",2)
                .orderByDesc("c.create_time"));
        ListResult<List<TwoLevelCommentRes>> listResult = new ListResult(count,list);

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, listResult , "");

    }

    /**
     * 回复二级评论
     * */
    @Override
    public BackResponseEntity<Object> replyTwoComment(ReplyTwoCommentReq replyTwoCommentReq){
        String userId = null;
        String bookId = null;
        String parentCommentId = null;
        String parentCommentUserId = null;
        String replyCommentId = null;
        String replyCommentUserId = null;
        String content = null;

        if(!ObjectUtils.isEmpty(replyTwoCommentReq.getUserId())){
            userId = replyTwoCommentReq.getUserId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(replyTwoCommentReq.getBookId())){
            bookId = replyTwoCommentReq.getBookId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(replyTwoCommentReq.getParentCommentId())){
            parentCommentId = replyTwoCommentReq.getParentCommentId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(replyTwoCommentReq.getParentCommentUserId())){
            parentCommentUserId  = replyTwoCommentReq.getParentCommentUserId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(replyTwoCommentReq.getReplyCommentId())){
            replyCommentId = replyTwoCommentReq.getReplyCommentId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(replyTwoCommentReq.getReplyCommentUserId())){
            replyCommentUserId = replyTwoCommentReq.getReplyCommentUserId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(replyTwoCommentReq.getContent())){
            content = replyTwoCommentReq.getContent()
                    .trim();
        }

        if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(bookId) || ObjectUtils.isEmpty(parentCommentId) || ObjectUtils.isEmpty(parentCommentUserId)
                || ObjectUtils.isEmpty(replyCommentId) || ObjectUtils.isEmpty(replyCommentUserId)|| ObjectUtils.isEmpty(content)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        BookComment bookComment = new BookComment();
        bookComment.setUserId(userId);
        bookComment.setBookId(bookId);
        bookComment.setParentCommentId(parentCommentId);
        bookComment.setParentCommentUserId(parentCommentUserId);
        bookComment.setReplyCommentId(replyCommentId);
        bookComment.setReplyCommentUserId(replyCommentUserId);
        bookComment.setContent(content);
        bookComment.setCommentLevel(2);
        bookComment.setCreateTime(LocalDateTime.now());

        int i = bookCommentMapper.insert(bookComment);

        if(i > 0){
            BooksInformation booksInformation = new BooksInformation();
            int count = booksInformationMapper.countCommentCount(bookId)+1;
            booksInformation.setBooksId(bookId);
            booksInformation.setCommentCount(count);

            booksInformationMapper.updateBooksInformation(booksInformation);

            return BackResponseEntity.success(ErrCodeEnum.unknown_0, "回复二级评论成功");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1024, "回复二级评论失败");
        }
    }

    /**
    * 查询我评论的
    * */
    @Override
    public BackResponseEntity<List<TwoLevelCommentRes>> querymyComment(DeleteReq deleteReq){
        String userId = null;

        if(!ObjectUtils.isEmpty(deleteReq.getId())){
            userId = deleteReq.getId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(userId)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        List<TwoLevelCommentRes> list = bookCommentMapper.querymyComment(Wrappers.<BookComment>query().eq("user_id",userId));

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, list,"查询我的评论成功");
    }

    /**
     * 查询评论我的
     * */
    @Override
    public BackResponseEntity<List<TwoLevelCommentRes>> queryreplymyComment(DeleteReq deleteReq){
        String userId = null;

        if(!ObjectUtils.isEmpty(deleteReq.getId())){
            userId = deleteReq.getId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(userId)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        List<TwoLevelCommentRes> list = bookCommentMapper.queryreplymyComment(Wrappers.<BookComment>query().eq("reply_comment_user_id",' ').eq("parent_comment_user_id",userId)
                .or().eq("reply_comment_user_id",userId));

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, list,"查询评论我的成功");
    }

    /**
     * 用户删除评论
     * 1.此评论的用户id和传过来的用户id相同
     * 2.如果此评论为一级评论，则该评论下所有二级评论会一起被删除
     * 3.如果此评论为二级评论，则只有该评论无效
     */
    @Override
    public BackResponseEntity<Object> deleteComments(DeleteCommmentReq deleteCommmentReq){
        String userId = null;
        String commentId = null;

        if(!ObjectUtils.isEmpty(deleteCommmentReq.getUserId())){
            userId = deleteCommmentReq.getUserId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(deleteCommmentReq.getUserId())){
            commentId = deleteCommmentReq.getCommentId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(commentId)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        BookComment bookComment = new BookComment();
        bookComment = bookCommentMapper.selectById(commentId);
        if(bookComment.getUserId().equals(userId) && bookComment.getCommentLevel() == 1){
            int i = bookCommentMapper.updateoneComment(Wrappers.<BookComment>query().eq("user_id",userId ).eq("id",commentId).or().eq("parent_comment_id",commentId));
            if(i > 0){
                BooksInformation booksInformation = new BooksInformation();
                int count  = booksInformationMapper.countCommentCount(bookComment.getBookId())-bookCommentMapper.countbooktwoComment(Wrappers.<BookComment>query().eq("parent_comment_id",commentId)
                        .eq("comment_level",2))-1;
                booksInformation.setBooksId(bookComment.getBookId());
                booksInformation.setCommentCount(count);

                booksInformationMapper.updateBooksInformation(booksInformation);
            }
        }

        if(bookComment.getCommentLevel() == 2 && bookComment.getUserId().equals(userId)){
            int i = bookCommentMapper.updateoneComment(Wrappers.<BookComment>query().eq("user_id",userId ).eq("id",commentId));
            if(i > 0){
                BooksInformation booksInformation = new BooksInformation();
                int count  = booksInformationMapper.countCommentCount(bookComment.getBookId())-1;
                booksInformation.setBooksId(bookComment.getBookId());
                booksInformation.setCommentCount(count);

                booksInformationMapper.updateBooksInformation(booksInformation);
            }
        }
        return BackResponseEntity.success(ErrCodeEnum.unknown_0, "删除评论成功");
    }
}

